// fiber_communication.cpp
#include <boost/fiber/all.hpp>
#include <iostream>
#include <vector>

// 使用 channel 进行 fiber 间通信
void producer(boost::fibers::buffered_channel<int>& chan, int count) {
    for (int i = 0; i < count; ++i) {
        chan.push(i);
        std::cout << "Produced: " << i << std::endl;
        boost::this_fiber::sleep_for(std::chrono::milliseconds(100));
    }
    chan.close();
}

void consumer(boost::fibers::buffered_channel<int>& chan, int id) {
    int value;
    while (boost::fibers::channel_op_status::success == chan.pop(value)) {
        std::cout << "Consumer " << id << " consumed: " << value << std::endl;
        boost::this_fiber::sleep_for(std::chrono::milliseconds(150));
    }
}

int main() {
    boost::fibers::buffered_channel<int> chan(3);  // 缓冲大小为3
    
    // 创建生产者和消费者 fibers
    boost::fibers::fiber producer_fiber(producer, std::ref(chan), 10);
    boost::fibers::fiber consumer_fiber1(consumer, std::ref(chan), 1);
    boost::fibers::fiber consumer_fiber2(consumer, std::ref(chan), 2);
    
    // 等待所有 fibers 完成
    producer_fiber.join();
    consumer_fiber1.join();
    consumer_fiber2.join();
    
    return 0;
}